package cn.wywk.netty.push.example.utils;

import cn.hutool.core.util.StrUtil;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @projectName:netty-push-example
 * @see:cn.wywk.netty.push.example.utils
 * @author:zhangwenxue
 * @createTime:2021/3/2 17:25
 * @version:1.0
 */
public class ThreadPoolManager<T> {
    //线程池名称
    private ThreadPool executor;
    //获取处理器数量
    private static int CPU_COUNT  = Runtime.getRuntime().availableProcessors();
    //默认回收时间
    private static int DEFAULT_KEEP_ALIVE_TIME   =  10;
    //阻塞任务队列数
    private static int DEFAULT_WATT_COUNT   =  200000;

    public ThreadPoolManager(String threadPoolName) {
        if (StrUtil.isBlank(threadPoolName)){
            throw new RuntimeException("threadPoolName is not null！！！");
        }
        executor = new ThreadPool(threadPoolName,corePoolSize(), maximumPoolSize(), keepAliveTime(), TimeUnit.SECONDS, wattingCount());
    }



    /**
     * @Description: 获取线程池对象
     * @Author: zhangwenxue
     * @Date: 2020/7/13 12:43
     */
    public static ThreadPool getExecutor(String threadPoolName){
        return new ThreadPoolManager(threadPoolName).executor;
    }


    /**
     * @Description: 不带返回值
     * @Author: zhangwenxue
     * @Date: 2020/7/13 12:11
     */
    public void execute(Runnable runnable) {
        executor.execute(runnable);
    }


    /**
     * @Description: 带有返回值的
     * @Author: zhangwenxue
     * @Date: 2020/7/13 12:11
     */
    public T submit(Runnable runnable) {
        return (T) executor.submit(runnable);
    }



    /**
     * @return corePoolSize
     *            核心线程池大小 the number of threads to keep in the pool, even if
     *            they are idle, unless {@code allowCoreThreadTimeOut} is set
     */
    private static int corePoolSize(){
        return Math.multiplyExact(CPU_COUNT,2);
    }

    /**
     * @return maximumPoolSize
     *            最大线程池大小 the maximum number of threads to allow in the pool
     */
    private static int maximumPoolSize(){
        return Math.multiplyExact(CPU_COUNT,2)+1;
    }

    /**
     * @return wattingCount
     *            阻塞任务队列数
     */
    private static int wattingCount(){
        return DEFAULT_WATT_COUNT;
    }

    /**
     * @return keepAliveTime
     *            线程池中超过corePoolSize数目的空闲线程最大存活时间 when the number of threads is
     *            greater than the core, this is the maximum time that excess
     *            idle threads will wait for new tasks before terminating.
     */
    private  static long keepAliveTime(){
        return DEFAULT_KEEP_ALIVE_TIME;
    }

}
